#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

#define in read()
#define pii pair<int,int>
#define fi first
#define se second
#define mes(x) memset(x,0,sizeof(x))
#define FILE(x) freopen(x".in","r",stdin);\
	freopen(x".out","w",stdout)

int read(){
	int x = 0,sgn = 1;char ch = getchar();
	for(;!isdigit(ch);ch = getchar()) if(ch == '-') sgn = -1;
	for(;isdigit(ch);ch = getchar()) x = (x<<1)+(x<<3)+(ch^48);
	return x*sgn;
}

const int MAXN = 1e6+10;

ll f[MAXN][2],ans;
int fa[MAXN],h[MAXN],cnt,n,val[MAXN],root;
bool vis[MAXN];
struct edge{int v,nxt;}e[MAXN<<1];
void link(int x,int y){e[++cnt] = (edge){y,h[x]};h[x] = cnt;}

void dfs(int x,int p){ 
	vis[x] = 1; f[x][0] = 0;f[x][1] = val[x];
	for(int i = h[x];i;i = e[i].nxt){
		int y = e[i].v; if(y == root) continue;
		dfs(y,x); f[x][0] += max(f[y][0],f[y][1]); f[x][1] += f[y][0];
	}
}

void fc(int x){
	root = x; vis[x] = 1;
	while(!vis[fa[root]]) root = fa[root],vis[root] = 1;
	dfs(root,0); ll t = f[root][0];
	root = fa[root]; dfs(root,0); ans += max(t,f[root][0]);
}

int main (){
	n = in;
	for(int i = 1;i <= n;i++) val[i] = in,fa[i] = in,link(fa[i],i);
	for(int i = 1;i <= n;i++) if(!vis[i]) fc(i);
	printf("%lld\n",ans);
	return 0;
}
